package com.example.s05_shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.s05_shop.mapper.OrdersItemMapper;
import com.example.s05_shop.mapper.OrdersMapper;
import com.example.s05_shop.mapper.ProductMapper;
import com.example.s05_shop.pojo.Orders;
import com.example.s05_shop.pojo.OrdersItem;
import com.example.s05_shop.pojo.Product;
import com.example.s05_shop.service.IOrdersService;
import com.example.s05_shop.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService
{
    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrdersItemMapper ordersItemMapper;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public boolean save(Orders o, List<OrdersItem> items)
    {
        // 插入订单
        int result = ordersMapper.insert(o);
        System.out.println(result);
        System.out.println("订单编号:"+o.getId());

        // 插入订单项
        for(OrdersItem oi:items)
        {
            // 设置订单项所属的订单编号
            oi.setOrdersId(o.getId());
            ordersItemMapper.insert(oi);
        }

        return true;
    }

    @Override
    public List<Orders> listByUserId(int uid)
    {

        // 1. 查询用户所有订单
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",uid);
        queryWrapper.orderByDesc("id");
        List<Orders> orders = ordersMapper.selectList(queryWrapper);

        // 2. 查询订单中的订单项
        for(Orders o:orders)
        {
            QueryWrapper<OrdersItem> qw2 = new QueryWrapper<>();
            qw2.eq("orders_id",o.getId());
            List<OrdersItem> items = ordersItemMapper.selectList(qw2);

            // 3。查询订单项产品
            for(OrdersItem i:items)
            {
                Product p = productMapper.selectById(i.getProductId());
                i.setProduct(p);
            }
            o.setItemList(items);
        }

        return orders;
    }
}
